package bacom;

import java.io.*;

public class RunBACOM {


    public static void main(String[] args) throws IOException {

	String normalCelFileName = null;
	String tumorCelFileName = null;
	String cdfFileName = null;
	String outputFileName = null; 

	if (args.length < 3 || args.length >= 5) {
	    System.out.println("\n  Not enough input files.");
	    return;
	} else if (args.length == 3) {

	    normalCelFileName = args[0];
	    tumorCelFileName = args[1];
	    cdfFileName = args[2];
	    outputFileName = "";

	} else if (args.length == 4) {

	    normalCelFileName = args[0];
	    tumorCelFileName = args[1];
	    cdfFileName = args[2];
	    outputFileName = args[3];

	}


	AffyCopyNumberData cnv;
	CopyNumberDetection cnvDetection;
	Noticcor D;

	cnv = new AffyCopyNumberData(normalCelFileName, tumorCelFileName, cdfFileName);
	
	cnvDetection = new CopyNumberDetection(cnv);

	if (cnv.isSuccessfulOpenFile && cnv.isSuccessfulOpenAnnotationFile) {

	    cnv.localNormalization();

	    cnvDetection = new CopyNumberDetection(cnv);

	    D = new Noticcor(cnv, cnvDetection);

	    D.correctNTC();

	    try {
 
		if (!(new File("results")).exists()) {
		    boolean isSucessful = (new File("results")).mkdir();
		}


		writeResults(cnv, cnvDetection, D, outputFileName);
	    } catch (Exception e) {
	    }

	} else {
	    if (!cnv.isSuccessfulOpenFile) {
		System.out.println("\n  Errors in reading CEL/CDF files." +
				   "\n  Please check input files.\n");
	    } else if (!cnv.isSuccessfulOpenAnnotationFile) {
		System.out.println("\n  Error in reading annotation files."
				   + "\n  Please make sure correct annotation files "
				   + "are placed under folder annotation.\n");
	    }
                 
	}

    }



    private static void writeResults(AffyCopyNumberData cnv, CopyNumberDetection cnvDetection,
				     Noticcor D, String fileName) throws IOException {
 
	BufferedWriter resultFile = null;

	double[] segMean = new double[cnv.probeSetID.length];

        int k = 0;
        for (int i = 0; i < cnvDetection.chromosome.size(); i++) {

            for (int j = cnvDetection.segStartPos.get(i); j <= cnvDetection.segEndPos.get(i); j++) {
                segMean[k] = cnvDetection.segStatus.get(i);
                k ++;
            }

        }


        try {
            resultFile = new BufferedWriter(new FileWriter("results/" + fileName + "data.csv"), 30*1024*1024);

	    for (int i = 0; i < cnv.probeSetID.length; i ++) {
		String entry = cnv.probeSetID[i] + "," + cnv.chrID[i] + "," + cnv.location[i] + ","
		    + cnv.copyNumber[i] + "," + segMean[i];
                resultFile.write(entry.toCharArray());
		resultFile.newLine();
            }
	} finally {
	    if (resultFile != null) {
                resultFile.close();
            }
        }



	BufferedWriter detectionResultFile = null;

        try {
            detectionResultFile = new BufferedWriter(new FileWriter("results/" + fileName + "detectionResult.csv"), 30*1024*1024);

	    for (int i = 0; i < cnvDetection.chromosome.size(); i ++) {
		String entry = cnvDetection.chromosome.get(i) + ","
		    + cnvDetection.segStartPos.get(i) + ","
		    + cnvDetection.segEndPos.get(i) + ","
		    + cnvDetection.segStatus.get(i);
		detectionResultFile.write(entry.toCharArray());
		detectionResultFile.newLine();
            }
	} finally {
	    if (detectionResultFile != null) {
                detectionResultFile.close();
            }
        }


	BufferedWriter correctionResultFile = null;

        try {
            correctionResultFile = new BufferedWriter(new FileWriter("results/" + fileName + "BACOMresults.txt"), 30*1024*1024);

	    for (int i = 0; i < D.deletionSegChrID.size(); i ++) {

		String entry = "Chr " + D.deletionSegChrID.get(i) + ":    from "
		    + D.deletionSegStartLocation.get(i)+ " to " + D.deletionSegEndLocation.get(i) + "\n     Pr of hemi="
		    + D.deletionSegProbHemiDeletion.get(i) + "\n     Pr of homo="
		    + D.deletionSegProbHomoDeletion.get(i) + "\n     Normal tissue fraction="
		    + D.deletionSegNormalTissueFraction.get(i) + "\n";

		correctionResultFile.write(entry.toCharArray());
		correctionResultFile.newLine();

            }

	    String entry = "The average normal tissue contamination fraction is " + D.alpha;
	    correctionResultFile.write(entry.toCharArray());
	    correctionResultFile.newLine();


	} finally {
	    if (correctionResultFile != null) {
                correctionResultFile.close();
            }
        }


        /*Write BACOM results with physical locations on the chromosomes   */

	correctionResultFile = null;

        try {
            correctionResultFile = new BufferedWriter(new FileWriter("results/" + fileName + "BACOM_locations.txt"), 30*1024*1024);

	    for (int i = 0; i < D.deletionSegChrID.size(); i ++) {

		String entry = "Chr " + D.deletionSegChrID.get(i) + ":    from "
		    + cnv.location[D.deletionSegStartLocation.get(i)]+ " to "
                    + cnv.location[D.deletionSegEndLocation.get(i)] + "\n     Pr of hemi-deletion="
		    + D.deletionSegProbHemiDeletion.get(i) + "\n     Pr of homo-deletion="
		    + D.deletionSegProbHomoDeletion.get(i) + "\n     Normal tissue fraction="
		    + D.deletionSegNormalTissueFraction.get(i) + "\n";

		correctionResultFile.write(entry.toCharArray());
		correctionResultFile.newLine();

            }

	    String entry = "The average normal tissue contamination fraction is " + D.alpha;
	    correctionResultFile.write(entry.toCharArray());
	    correctionResultFile.newLine();


	} finally {
	    if (correctionResultFile != null) {
                correctionResultFile.close();
            }
        }


    }






}